package com.hoyo.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hoyo.common.AppConstant;
import com.hoyo.common.VerifyCode;
import com.hoyo.config.MainFinalConfig;
import com.hoyo.config.UserRealm.Principal;
import com.hoyo.domain.Catalog;
import com.hoyo.domain.User;
import com.hoyo.domain.UserInfo;
import com.hoyo.service.CatalogService;
import com.hoyo.service.UserService;
import com.hoyo.utils.CommonUtils;
import com.hoyo.utils.MailUtils;
import com.hoyo.utils.MessageUtils;

@Controller
public class UserController{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CatalogService catalogService;
	
	private Logger logger = Logger.getLogger(LoginController.class);

	@RequestMapping(value="/register", method=RequestMethod.POST)
	@ResponseBody
	public String register(@ModelAttribute("user") @Validated UserInfo info
			,HttpSession session, BindingResult bResult, JSONObject result) throws Exception{
		
		logger.info(this.getClass().getName());
		Map<String, String> errors = CommonUtils.resultValidate(bResult);
		if(errors.size()<=0){
//			VerifyCode verifyCode = (VerifyCode) session.getAttribute("verifyCode");
//			System.out.println("verify code from session:" + verifyCode.toString());
			System.out.println(info.toString());
//			if(CommonUtils.checkCodeAvailable(info.getVerifyCode(), verifyCode)){
//				verifyCode.setEnable(false);
				info.setPassword(new Md5Hash(info.getPassword(), MainFinalConfig.SALT).toHex());
				userService.register(info);
				result.put("success", true);
//			}else{
//				result.put("success", false);
//				result.put("error", "验证码不正确或已失效");
//			}
		}else{
			result.put("success", false);
			result.put("error", errors);
		}
		
		return result.toString();
	}
	
	@RequestMapping(value="/email/check", method=RequestMethod.POST)
	@ResponseBody
	public String emailCheckRepeat(@RequestParam("email") String email
			, JSONObject result) throws Exception{
		
		if(userService.emailRepeatCheck(email)){
			result.put("success", true);
			result.put("message", "邮箱地址"+email+"已被使用");
		}else{
			result.put("success", false);
		}
		
		return result.toString();
	}
	
	@RequestMapping(value="/telephone/check", method=RequestMethod.POST)
	@ResponseBody
	public String telephoneCheckRepeat(@RequestParam("telephone") String telephone
			, JSONObject result) throws Exception{
		
		if(userService.telephoneRepeatCheck(telephone)){
			result.put("success", false);
			result.put("message", "手机号码"+telephone+"已被使用");
		}else{
			result.put("success", true);
		}
		
		return result.toString();
	}
	
	@RequestMapping(value="/email/code", method=RequestMethod.POST)
	@ResponseBody
	public String emailVerifyCode(@RequestParam("email") String email
			,HttpSession session, JSONObject result) throws Exception{
		
		String code = CommonUtils.generateVerifyCode();
		MailUtils.send("hoyo", String.format(AppConstant.MESSAGE_CODE_TEMPLATE, code), email);
		
		VerifyCode verifyCode = new VerifyCode(code, System.currentTimeMillis(), 60*1000, true);
		session.setAttribute("verifyCode", verifyCode);
		result.put("success", true);
		return result.toString();
	}
	
	@RequestMapping(value="/telephone/code", method=RequestMethod.POST)
	@ResponseBody
	public String telephoneVerifyCode(@RequestParam("telephone") String telephone
			,HttpSession session, JSONObject result) throws Exception{
		
		String code = CommonUtils.generateVerifyCode();
		String params = "{\"code\":\""+code+"\",\"product\":\"hoyo\"}";
		boolean success = MessageUtils.send(telephone, AppConstant.Message.TEMPLATE_CODE, params);
		VerifyCode verifyCode = new VerifyCode(code, System.currentTimeMillis(), 60*1000, true);
		session.setAttribute("verifyCode", verifyCode);
		result.put("success", success);

		return result.toString();
	}
	
	@RequestMapping(value="/code/verify", method=RequestMethod.POST)
	@ResponseBody
	public String codeVerify(@RequestParam("code") String code
			,HttpSession session, JSONObject result) throws Exception{
		
		VerifyCode verifyCode = (VerifyCode) session.getAttribute("verifyCode");
		if(CommonUtils.checkCodeAvailable(code, verifyCode)){
			verifyCode.setEnable(false);
			result.put("success", true);
		}else{
			result.put("success", false);
			result.put("error", "验证码不正确或已失效");
		}
		
		return result.toString();
	}
	
	/*
	@RequestMapping(value="/user/password/modify", method=RequestMethod.POST)
	public ResultMessage passwordModify(@RequestParam("password") String password
			,ResultMessage result) throws Exception{
		
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		
		userService.modifyPassword(username, password);
		
		return result.success(true);
	}*/
	
	@RequestMapping(value="/user/email/code", method=RequestMethod.GET)
	@ResponseBody
	public String emailModifyCode(HttpSession session, JSONObject result) throws Exception{
		
		Subject subject = SecurityUtils.getSubject();
		VerifyCode verifyCode = userService.sendEmailCode(((String)subject.getPrincipal()));
		session.setAttribute("verifyCode", verifyCode);
		result.put("success", true);
		return result.toString();
	}
	
	@RequestMapping(value="/user/email/bind", method=RequestMethod.POST)
	@ResponseBody
	public String bindEmail(@RequestParam("email") String email,
			HttpSession session,JSONObject result) throws Exception{
		
		Subject subject = SecurityUtils.getSubject();
		userService.bindEmail(((String)subject.getPrincipal()), email);
		result.put("success", true);
		return result.toString();
	}
	
	@RequestMapping(value="/user/telephone/code", method=RequestMethod.GET)
	@ResponseBody
	public String telephoneModifyCode(HttpSession session, JSONObject result) throws Exception{
		
		//Subject subject = ;
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		VerifyCode verifyCode = userService.sendTelephoneCode(principal.toString());
		session.setAttribute("verifyCode", verifyCode);
		result.put("success", true);
		return result.toString();
	}
	
	
	@RequestMapping(value="/user/telephone/bind", method=RequestMethod.POST)
	@ResponseBody
	public String bindTelephone(@RequestParam("telephone") String telephone,
			@RequestParam("code") String code, HttpSession session, 
			JSONObject result){

		VerifyCode verifyCode = (VerifyCode) session.getAttribute("verifyCode");
		if(CommonUtils.checkCodeAvailable(code, verifyCode)){
			verifyCode.setEnable(false);
			Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
			try {
				userService.bindTelephone(principal.toString(), telephone);
				User user = (User)session.getAttribute("user");
				user.setPhone(telephone);
				principal.setUser(user);
				session.setAttribute("user", user);
				result.put("success", true);
				result.put("msg", "更换绑定手机成功");
			} catch (Exception e) {
				e.printStackTrace();
				result.put("success", false);
				result.put("msg", "更换绑定手机失败");
			}	
		}else{
			result.put("success", false);
			result.put("msg", "验证码不正确或已失效");
		}
		
		return result.toString();
	}
	
	@RequestMapping(value="/user/password/modify", method=RequestMethod.POST)
	@ResponseBody
	public String modifyPassword(@RequestParam("password") String password, 
			HttpSession session, JSONObject result){
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		try {
			userService.modifyPassword(principal.toString(), password);
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
		}
		return result.toString();
	}
	

	@RequestMapping("/user/personalCenter")
	public ModelAndView personalCenter(HttpSession session) throws Exception{
		
		ModelAndView mav = new ModelAndView("usercenter.html");
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		User user = userService.findByIdentifier(principal.toString());
		UserInfo userInfo = userService.findUserInfoByUserId(user.getId());
		List<Catalog> catalog = catalogService.findCatalogsByAccountId(user.getId());
		System.out.println(catalog);
		mav.addObject("userInfo", userInfo);
		mav.addObject("cataLog",catalog);
		return mav;
	}

	
	/*@RequestMapping("/user/profile")
	public ModelAndView showProfile(HttpSession session) throws Exception{
		
		Subject subject = SecurityUtils.getSubject();
		UserInfo info = userService.lookup(((String)subject.getPrincipal()));
		
		ModelAndView mav = new ModelAndView("user_profile");
		mav.addObject("info", info);
		return mav;
	}*/
	
	/*
	 * 个人信息页面
	 */
	@RequestMapping("/user/personInfo")
	public ModelAndView personInfo() throws Exception {
		ModelAndView mav = new ModelAndView("personinfo.html");
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		User user = userService.findByIdentifier(principal.toString());
		UserInfo userInfo = userService.findUserInfoByUserId(user.getId());
		mav.addObject("userInfo", userInfo);
		return mav;
	}
	
	
	/*
	 * 修改个人信息
	 */
	@RequestMapping("/user/updatePersonInfo")
	@ResponseBody
	public String updatePersonInfo(@RequestBody UserInfo userInfo,HttpSession session) {
		
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		try {
			userInfo.setUserId(principal.getUser().getId());
			userService.updatePersonInfo(userInfo);
			session.setAttribute("userInfo", userService.findUserInfoByUserId(principal.getUser().getId()));
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
		return "success";
	}
	
	
	@RequestMapping("/user/safeCenter")
	public ModelAndView safeCenter() throws Exception{
		ModelAndView mav = new ModelAndView("safecenter.html");
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		User user = userService.findByIdentifier(principal.toString());
		UserInfo userInfo = userService.findUserInfoByUserId(user.getId());
		mav.addObject("user", user);
		mav.addObject("userInfo", userInfo);	
		return mav;
	}
	
	@RequestMapping("/user/modifytele")
	public ModelAndView modifytele() throws Exception{
		ModelAndView mav = new ModelAndView("modifytele.html");
		/*Principal Principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		User user = userService.findByIdentifier(Principal.getTelephone());
		UserInfo userInfo = userService.findUserInfoByUserId(user.getId());
		mav.addObject("user", user);
		mav.addObject("userInfo", userInfo);*/
		return mav;
	}
	
	@RequestMapping("/user/modifypwd")
	public ModelAndView modifypwd() throws Exception{
		ModelAndView mav = new ModelAndView("modifypwd.html");
		/*Principal Principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		User user = userService.findByIdentifier(Principal.getTelephone());
		UserInfo userInfo = userService.findUserInfoByUserId(user.getId());
		mav.addObject("user", user);
		mav.addObject("userInfo", userInfo);*/
		return mav;
	}
	
	
	@RequestMapping("/user/modifyicon")
	public ModelAndView modifyicon() throws Exception{
		ModelAndView mav = new ModelAndView("modifyicon.html");
		/*Principal Principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		User user = userService.findByIdentifier(Principal.getTelephone());
		UserInfo userInfo = userService.findUserInfoByUserId(user.getId());
		mav.addObject("user", user);
		mav.addObject("userInfo", userInfo);*/
		return mav;
	}

		
	@RequestMapping(value="/user/icon/modify", method=RequestMethod.POST)
	@ResponseBody
	public String modifyIcon(@RequestParam("icon") String icon,HttpSession session,JSONObject result){
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		String realPath = AppConstant.Qiniuyun.publicDomain +"/"+ icon;
		try {
			userService.modifyIconInfo(principal.toString(), realPath);
			UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");
			userInfo.setIcon(realPath);
			session.setAttribute("userInfo", userInfo);
			principal.setUserInfo(userInfo);
			result.put("success", true);
			result.put("msg", "更改头像成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
			result.put("msg", "更改头像失败");
		}
		
		return result.toString();
	}
	
	@RequestMapping("/user/userLikeCatalog")
	public ModelAndView userLikeCatalog(HttpSession session){
		ModelAndView mav =new  ModelAndView("userLikeCatalog.html");
		
		try {
			/*Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
			User user = userService.findByIdentifier(principal.toString());
			UserInfo userInfo = userService.findUserInfoByUserId(user.getId());
			mav.addObject("user", user);
			mav.addObject("userInfo", userInfo);*/
			List<Catalog> catalogs = catalogService.findUserLikeCatalogByUserId(((User)(session.getAttribute("user"))).getId());
			System.out.println(catalogs);
			mav.addObject("catalogs", catalogs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return mav;
	}
	
}	









